// 设置， 修改个人资料
const router = require('express').Router()
const db = require('../db')

// 修改密码
router.get('/updataPass', (req, res) => {
    let { pass, oldPass, user } = req.query
    if (pass && oldPass) {
        db.query(`SElECT id FROM ${user.role} WHERE password = '${oldPass}';`, [], result => {
            if (result[0] && result[0].id) {
                db.query(`update ${user.role} set password = '${pass}' where id = '${user.id}';`)
                res.json({ code: 0, msg: '密码修改成功', type: 'success' })
            } else {
                res.json({ code: 400, msg: '密码输入错误', type: 'warning' })
            }
        })
    } else {
        res.json({ code: 400, msg: 'no params' })
    }
})
// 查询个人信息
router.get('/query', (req, res) => {

    let { role, id } = req.query.user
    if (role === 'student') {
        db.query(`SELECT  *  FROM class_student_view WHERE studentId = '${id}'; `, [], result => {
            res.json({
                code: 0,
                data: result
            })
        })
    } else if (role === 'teacher') {
        var data = {}
        /*db.query(` SELECT sex, specialty FROM teacher WHERE id='${id}'; `, [], result => {
            data = {
                sex: result[0].sex,
                specialty: result[0].specialty,
                teacherClassList: []
            }
            db.query(`SELECT * FROM teacher_class WHERE teacher = '${id}';`, [], result => {
                let params = []
                result.map((item, i) => {
                    params[i] = item.class
                })
                db.query(`SELECT * FROM class WHERE id IN(?)`, [params], result2 => {
                    result2.map((item) => {
                        data.teacherClassList.push(item)
                    })
                    res.json({
                        code: 0,
                        data
                    })
                })
            })
        })*/
        db.query(`SELECT id, name, sex, specialty FROM teacher WHERE id = ${id}`, {}, data => {
            res.json({ code: 0, data })
        })
    } else {
        db.query(`SELECT id, name, sex FROM admin WHERE id = ${id}`, {}, data => {
            res.json({ code: 0, data })
        })
    }

})

// 修改信息
router.get('/editor', (req, res) => {
    let data = JSON.parse(req.query.data)
    let oldId = req.query.oldId
    let table = req.query.table
    let user = req.query.user
    if (table === user.role) {
        res.json({ code: 403, msg: 'no permission' })
        return
    }
    console.log('data', data)
    db.query(`UPDATE ${table} SET ? WHERE id=?`, [data, oldId], result => {
        res.json({ code: 0, msg: '修改成功', type: 'success' })
    })
})

module.exports = router